//
//  RCChoosePointMapViewController.m
//  RocketProject
//
//  Created by Wu Chengwei on 13-11-19.
//  Copyright (c) 2013年 Rocket. All rights reserved.
//

#import "RCChoosePointMapViewController.h"
#import "RCPointAnnotation.h"
#import "UIColor-Expanded.h"
#import "CommonDefines.h"
#import "BMKSearch.h"
#import "BMapKit.h"
#import "GloableEngineService.h"
#import "NSString+NSString_Ex_.h"

#define METERS_PER_MILE 1609.344

#define kImageCurrentLocation             @"image_map_currentLocation.png"
#define kImageChooseLocation              @"image_map_chooseLocation.png"
#define kImageCommitButton                @"image_map_commit.png"
#define kImageCommitBGImage               @"image_map_commit_bg.png"

@interface RCChoosePointMapViewController ()<BMKSearchDelegate,GloableChoosePointDelegate>

@property (nonatomic, retain) MKMapView *mapView;

@property (nonatomic,assign) CLLocationCoordinate2D lastChooseCoor;
@property(nonatomic,retain) UILabel *locationLabel;
@property(nonatomic,retain) UIButton *commitButton;
@property(nonatomic,retain) UIButton *locationButton;
@property(nonatomic,retain) CLGeocoder *geocoder;

@end

@implementation RCChoosePointMapViewController{
    CLLocationCoordinate2D coor;
    NSString               *_pointTitle;
}

@synthesize pointTitle = _pointTitle;
@synthesize mapView = _mapView;
@synthesize lastChooseCoor = _lastChooseCoor;
@synthesize locationLabel = _locationLabel;
@synthesize commitButton = _commitButton;
@synthesize locationButton = _locationButton;
@synthesize delegate = _delegate;
@synthesize geocoder = _geocoder;


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle



- (id) initWithCoor:(CLLocationCoordinate2D)coordinate andName:(NSString *)title
{
    self = [super init];
    if (self) {
        coor = coordinate;
        self.lastChooseCoor = coordinate;
        self.pointTitle = title;
        _geocoder = [[CLGeocoder alloc]init];
    }
    
    return self;
}


- (void) dealloc
{
    self.delegate = nil;
    self.pointTitle = nil;
    self.mapView = nil;
    self.locationLabel = nil;
    self.commitButton = nil;
    self.locationButton = nil;
    self.geocoder = nil;
    [super dealloc];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.titleLabelText = @"地图选点";
    self.navigationItem.titleView = [self createTitleView];
    
	// Do any additional setup after loading the view, typically from a nib.
    _mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, 320, UIScreenHeight-45-64)];
    [self.viewContainer addSubview:_mapView];
    [_mapView setShowsUserLocation:YES];

    
    _mapView.delegate = self;
    
    MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(coor, 0.5*METERS_PER_MILE, 0.5*METERS_PER_MILE);
    [_mapView setRegion:viewRegion animated:YES];
    
    
    UIImageView *choosePointImageView = [[UIImageView alloc]initWithImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:kImageChooseLocation ofType:nil]]];
    choosePointImageView.center = _mapView.center;
    [self.viewContainer addSubview:choosePointImageView];
    [choosePointImageView release];
    
    _locationButton = [[UIButton alloc]initWithFrame:CGRectMake(15, _mapView.frame.size.height-70, 60, 40)];
    _locationButton.backgroundColor = [UIColor clearColor];
    [_locationButton setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:kImageCurrentLocation ofType:nil]] forState:UIControlStateNormal];
    [_locationButton setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:kImageCurrentLocation ofType:nil]] forState:UIControlStateHighlighted];
    [_locationButton addTarget:self action:@selector(loctionButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.viewContainer addSubview:_locationButton];
    
    UIImageView *bannerView = [[UIImageView alloc]initWithFrame:CGRectMake(0, UIScreenHeight-45-64, 320, 45)];
    bannerView.backgroundColor = [UIColor clearColor];
    bannerView.userInteractionEnabled = YES;
    [bannerView setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle]pathForResource:kImageCommitBGImage ofType:nil]]];
    
    _locationLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 15, 200, 16)];
    _locationLabel.backgroundColor = [UIColor clearColor];
    _locationLabel.textColor = [UIColor colorWithHex:0xff505050];
    _locationLabel.font = [UIFont fontWithName:kFontNameLightHeiti size:16];
    [bannerView addSubview:_locationLabel];
    
    _commitButton = [[UIButton alloc]initWithFrame:CGRectMake(245, 8, 65, 30)];
    _commitButton.backgroundColor = [UIColor clearColor];
    [_commitButton setTitle:@"提交" forState:UIControlStateNormal];
    [_commitButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _commitButton.titleLabel.font = [UIFont fontWithName:kFontNameLightHeiti size:15];
    [_commitButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:kImageCommitButton ofType:nil]] forState:UIControlStateNormal];
    [_commitButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:kImageCommitButton ofType:nil]] forState:UIControlStateHighlighted];
    [_commitButton addTarget:self action:@selector(commitButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [bannerView addSubview:_commitButton];
    
    [self.viewContainer addSubview:bannerView];
    [bannerView release];
    
	
    _commitButton.enabled = NO;

    
}



-(void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
    CGPoint pt = self.mapView.center;
    CLLocationCoordinate2D latLong = [self.mapView convertPoint:pt toCoordinateFromView:self.mapView];
    if (self.lastChooseCoor.latitude != latLong.latitude || self.lastChooseCoor.longitude != latLong.longitude) {
        self.lastChooseCoor = latLong;
        
        
        CLLocation *location = [[CLLocation alloc]initWithLatitude:latLong.latitude longitude:latLong.longitude];
        _locationLabel.text = @"正在解析中...";
        _commitButton.enabled = NO;
        [_geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
            
            if (error != nil) {
                _locationLabel.text = @"解析失败，请稍后重试";
                _commitButton.enabled = NO;
            }else{
                
                for (CLPlacemark *place in placemarks) {
                    if (![NSString stringIsNullOrEmpty:place.locality]) {
                        NSString *subLocality = place.subLocality;
                        NSString *thoroughfare = place.thoroughfare;
                        
                        if ([NSString stringIsNullOrEmpty:subLocality]) {
                            subLocality = @"";
                        }
                        
                        if ([NSString stringIsNullOrEmpty:thoroughfare]) {
                            thoroughfare = @"";
                        }
                        
                        _locationLabel.text = [NSString stringWithFormat:@"%@%@%@",place.locality,subLocality,thoroughfare];
                        _commitButton.enabled = YES;
                        break;
                    }
                }
                
            }
            
            
        }];
        
        [location release];
        
    }
    
    KFLog(@"lat %lf lon %lf",latLong.latitude,latLong.longitude);
}

-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
    
    [self.mapView setCenterCoordinate:self.mapView.userLocation.coordinate animated:YES];
    self.mapView.showsUserLocation = NO;
    
    
    
    CLLocation *location = [[CLLocation alloc]initWithLatitude:self.mapView.userLocation.coordinate.latitude longitude:self.mapView.userLocation.coordinate.longitude];
    _locationLabel.text = @"正在解析中...";
    _commitButton.enabled = NO;
    [_geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        if (error != nil) {
            _locationLabel.text = @"解析失败，请稍后重试";
            _commitButton.enabled = NO;
        }else{
            
            for (CLPlacemark *place in placemarks) {
                if (![NSString stringIsNullOrEmpty:place.locality]) {
                    NSString *subLocality = place.subLocality;
                    NSString *thoroughfare = place.thoroughfare;
                    
                    if ([NSString stringIsNullOrEmpty:subLocality]) {
                        subLocality = @"";
                    }
                    
                    if ([NSString stringIsNullOrEmpty:thoroughfare]) {
                        thoroughfare = @"";
                    }
                    
                    _locationLabel.text = [NSString stringWithFormat:@"%@%@%@",place.locality,subLocality,thoroughfare];
                    _commitButton.enabled = YES;
                    break;
                }
            }
            
        }
        
    }];
    
    [location release];
}

-(void)mapView:(MKMapView *)mapView didFailToLocateUserWithError:(NSError *)error{
    self.mapView.userLocation.coordinate = coor;
    
    //发起反地理编码
    CLLocation *location = [[CLLocation alloc]initWithLatitude:coor.latitude longitude:coor.longitude];
    _locationLabel.text = @"正在解析中...";
    _commitButton.enabled = NO;
    [_geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        if (error != nil) {
            _locationLabel.text = @"解析失败，请稍后重试";
            _commitButton.enabled = NO;
        }else{
            
            for (CLPlacemark *place in placemarks) {
                if (![NSString stringIsNullOrEmpty:place.locality]) {
                    NSString *subLocality = place.subLocality;
                    NSString *thoroughfare = place.thoroughfare;
                    
                    if ([NSString stringIsNullOrEmpty:subLocality]) {
                        subLocality = @"";
                    }
                    
                    if ([NSString stringIsNullOrEmpty:thoroughfare]) {
                        thoroughfare = @"";
                    }
                    
                    _locationLabel.text = [NSString stringWithFormat:@"%@%@%@",place.locality,subLocality,thoroughfare];
                    _commitButton.enabled = YES;
                    break;
                }
            }
            
        }
        
    }];
    
    [location release];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

//-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
//    CGPoint pt = [[touches anyObject]locationInView:self.mapView];
//    CLLocationCoordinate2D latLong = [self.mapView convertPoint:pt toCoordinateFromView:self.mapView];
//    KFLog(@"lat %lf lon %lf",latLong.latitude,latLong.longitude);
//}

-(void)commitButtonClicked{
    NSString *addressString = _locationLabel.text;
    if (_delegate && [_delegate respondsToSelector:@selector(chooseMerchantAddress:)]) {
        [_delegate chooseMerchantAddress:addressString];
        
    }
    
    if (_delegate && [_delegate respondsToSelector:@selector(chooseMerchantAddress:withCoor:)]) {
        [_delegate chooseMerchantAddress:addressString withCoor:self.lastChooseCoor];
    }
    
    [self leftButtonClicked];
}

-(void)loctionButtonClicked{
    
    [self.mapView setCenterCoordinate:self.mapView.userLocation.coordinate animated:YES];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [GloableEngineService sharedInstance].delegate = self;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
    
}

-(void)leftButtonClicked{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
    [GloableEngineService sharedInstance].delegate = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}


@end
